import remoteLoad from './remoteLoad';
const { AMapCDN, AMapUiCDN } = require('@/plugins/cdn');

/**
 * 用于将地址后面的参数转换成对象返回
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
    const search = url.split('?')[1];
    if (!search) {
        return {};
    }
    return JSON.parse(
        '{"' +
        decodeURIComponent(search)
            .replace(/"/g, '\\"')
            .replace(/&/g, '","')
            .replace(/=/g, '":"')
            .replace(/\+/g, ' ') +
        '"}'
    );
}

/**
 * 函数防抖
 * @param {Function} func
 * @param {number} delay
 * @param {boolean} immediate
 * @return {*}
 */

export function debounce(func, delay, immediate = false) {
    let timer,
        context = this;
    return (...args) => {
        if (immediate) {
            func.apply(context, args);
            immediate = false;
            return;
        }
        clearTimeout(timer);
        timer = setTimeout(() => {
            func.apply(context, args);
        }, delay);
    };
}

/**
 * 获取geoJson数据  通过高德获取    递归获取区县geoJson
 * @param  {string} adcode  行政区code
 * @param  {string} childAdcode 区县级行政区code
 * @return {Array}
 */
export function getGeoJson(adcode, childAdcode = '') {
    return new Promise((resolve, reject) => {
        if (window.AMap && window.AMapUI) {
            insideFun(adcode, childAdcode);
        } else {
            remoteLoad(AMapCDN).then(() => {
                if (window.AMap) {
                    remoteLoad(AMapUiCDN).then(() => {
                        if (window.AMapUI) {
                            insideFun(adcode, childAdcode);
                        } else {
                            console.error('AMapUI获取失败');
                        }
                    });
                } else {
                    console.error('AMap获取失败');
                }
            });
        }
        function insideFun(adcode, childAdcode) {
            // eslint-disable-next-line
            AMapUI.loadUI(['geo/DistrictExplorer'], DistrictExplorer => {
                var districtExplorer = new DistrictExplorer();
                districtExplorer.loadAreaNode(adcode, function (error, areaNode) {
                    if (error) {
                        console.error(error);
                        reject(error);
                        return;
                    }
                    let Json = areaNode.getSubFeatures();
                    if (Json.length === 0) {
                        let parent = areaNode._data.geoData.parent.properties.acroutes;
                        insideFun(parent[parent.length - 1], adcode);
                        return;
                    }

                    if (childAdcode) {
                        Json = Json.filter(item => {
                            return item.properties.adcode == childAdcode;
                        });
                    }
                    let mapJson = {
                        features: Json
                    };
                    resolve(mapJson);
                });
            });
        }
    });
}

/**
 * 转换JSON  导出
 * @param  {Array}
 * @return {Array}
 */

export function formatJson(arr, filterVal) {
    return arr.map(v => filterVal.map(j => v[j].toString()));
}

// 定义一个深拷贝函数
export function deepClone(target) {
    // 定义一个变量
    let result;
    // 如果当前需要深拷贝的是一个对象的话
    if (typeof target === 'object') {
        // 如果是一个数组的话
        if (Array.isArray(target)) {
            result = []; // 将result赋值为一个数组，并且执行遍历
            for (let i in target) {
                // 递归克隆数组中的每一项
                result.push(deepClone(target[i]))
            }
            // 判断如果当前的值是null的话；直接赋值为null
        } else if (target === null) {
            result = null;
            // 判断如果当前的值是一个RegExp对象的话，直接赋值    
        } else if (target.constructor === RegExp) {
            result = target;
        } else {
            // 否则是普通对象，直接for in循环，递归赋值对象的所有值
            result = {};
            for (let i in target) {
                result[i] = deepClone(target[i]);
            }
        }
        // 如果不是对象的话，就是基本数据类型，那么直接赋值
    } else {
        result = target;
    }
    // 返回最终结果
    return result;
}